#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Time   :2020/8/7 10:25
# Author : fengzhilaoling
import random
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
from django.conf import settings
from django.core.cache import cache
from io import BytesIO


def range_code():
    # 生成随机4位数
    metadata = 'qwertyuiopasdfghjklzxcvbnm1234567890'
    code = ''
    for i in range(4):
        code += random.choice(metadata)
    return code


def range_colour():
    # 生成随机颜色
    color_list = []
    for i in range(3):
        color_num = random.randint(0, 256)
        color_list.append(color_num)
    color_tuple = tuple(color_list)
    return color_tuple


def range_location(num=2):
    xy_list = [random.randrange(80), random.randrange(50)]
    for i in range(num - 2):
        xy_list.append(random.randrange(80))
    xy_tuple = tuple(xy_list)
    return xy_tuple


def create_image():
    mode = 'RGB'  # 画布模式
    size = (80, 45)  # 画布大小
    color_bg = range_colour()  # 画布的背景颜色，随机
    image = Image.new(mode=mode, size=size, color=color_bg)  # 生成画布
    draw = ImageDraw.Draw(image, mode=mode)  # 生成画笔
    font = settings.FONT_DIR
    # font = 'status/plug_in/msyh.ttc'
    # font = 'D:\python web练习\Django框架\django_practice\verify_code_dome\verify_code\myapp\static\plug_in\msyh.ttc'
    # 设置书写字体和大小
    font = ImageFont.truetype(font=font, size=30)
    # 获取验证码
    code = range_code()
    # 循环书写验证码
    for i in range(len(code)):
        draw.text(xy=(20 * i, 0), fill=range_colour(), font=font, text=code[i])
    # 添加干扰点
    for i in range(150):
        draw.point(range_location(), fill=range_colour())
    # 添加干扰线和干扰弧线
    for i in range(10):
        draw.line(range_location(4), fill=range_colour(), width=random.randrange(3))
        draw.arc(range_location(4), random.randrange(360), random.randrange(360), fill=range_colour(), width=random.randrange(3))
    # 存储到内存流
    output = BytesIO()
    image.save(output, format='png')
    # 存储到缓存中，一般是redis中，需要在settings中配置redis，这里没配存储到了内存中
    cache.set('image', output.getvalue(), 62)
    cache.set('code', code, 62)
    output.close()  # 关闭内存流

